<template>
  <div class="chat-container">
    <!-- Right side: Chat box -->
    <div class="right-side">
      <!-- Chat header -->
      <div class="chat-header">
        <span v-if="currentUser">{{ currentUser.userName }}</span>
      </div>
      <!-- Chat messages -->
      <el-scrollbar class="chat-messages" ref="messageContainer">
        <div class="messageBox" v-for="message in messages" >
          <div><img :src="logo" alt="" style="border: 1px solid #70c1fa;"></div>
          <div class="messageContent">{{ message.content }}</div>
          <div class="messageTime"></div>
        </div>
      </el-scrollbar>
      <div class="chat-input">
        <el-input v-model="newMessage.content" placeholder="请输入聊天内容" autosize class="message-input" @keydown.enter.native="sendMessage"></el-input>
        <el-button type="primary" @click.native="sendMessage" class="send-button">发送</el-button>
      </div>
    </div>
  </div>
</template>
<script>
import { sendMessageTo } from '@/api/websocket/websocket'
import websocket from '@/api/websocket/websocketUtil'
import logo from '@/assets/logo/logo.jpg'

export default {
  data () {
    return {
      logo,
      currentUser: null, // 当前聊天的人
      loginUser: {
        userId :"1",

      },
      messages: [],
      messageForm: [], // 聊天所有信息
      newMessage: {
        handle: '',
        sendUser: '',
        receiveUser: '',
        content: '',
        is_read: '0',
        createTime: ''
      },
      searchUserName: ''
    }
  },
  methods: {
    async fetchMessages (userId) {

    },
    sendMessage () {
      if (!this.newMessage.content.trim()) {
        this.$message.warning('请输入聊天内容')
        return
      }
      this.sendWebSocketMessage(this.newMessage)
      sendMessageTo(this.newMessage).then(res => {
        if (res.code !== 200) {
          this.$message.error(res.message)
          return
        }
        console.log(res.data)
        this.messages = [res.data]
        console.log(this.messages)
        // 将聊天记录总下拉到最下方
        this.$nextTick(() => {
          this.scrollToBottom()
        })
      })
    },
    // 消息过多的时候滚动到最新消息位置
    scrollToBottom () {
      // 使用 $refs 来获取对消息容器的引用
      const container = this.$refs.messageContainer.$refs.wrap
      // 滚动到底部
      container.scrollTop = container.scrollHeight
    },
    checkAvatar (avatar) {
      if (avatar && avatar !== undefined) {
        return avatar
      }
      return ''
    },
    chooseUser (user) {
      this.currentUser = user
      this.fetchMessages(user.userId)
    },
    // websocket
    async connectWebSocket () {
      await new Promise((resolve) => {
        websocket.Init()
        // 在 WebSocket 连接成功时调用 resolve
        websocket.getWebSocket().onopen = () => {
          console.log('WebSocket连接成功')
          resolve()
        }
      })
    },
    // 发送信息
    sendWebSocketMessage (message) {
      websocket.getWebSocket().onmessage = (event) => {
        // 处理消息，这里你可以根据实际需求更新页面上的数据
        console.log('收到的消息WebSocket2:', event)
        // 更新收到的消息
        // receivedMessage.value = event.data
        if (this.currentUser) {
          this.fetchMessages(this.currentUser.userId)
        } else {
          this.fetchMessages()
        }
      }
    },
    handleMessage (message) {
      // 内容进行相应的处理
      const parsedMessage = JSON.parse(message)
      console.log('收到信息:', parsedMessage)
      if (this.currentUser) {
        this.fetchMessages(this.currentUser.userId)
      } else {
        this.fetchMessages()
      }
    },

  },
  mounted () {

  },
  created () {
    this.$store.dispatch('GetInfo')
    this.connectWebSocket()
  },

}
</script>

<style scoped>

.chat-container {
  display: flex;
  height: 100vh;
  background: linear-gradient(to bottom right, #FFFFFF, #ECEFF1);
}

.right-side {
  flex: 3;
  display: flex;
  flex-direction: column;
}

.chat-header {
  padding: 20px;
  border-bottom: 1px solid #eaeaea;
  font-size: 1.2em;
  color: #37474F;
}

.chat-messages {
  flex: 1;
  overflow-y: auto;
  padding: 20px;
}

.chat-input {
  padding: 20px;
  display: flex;
  align-items: center;
}

.message-input {
  flex: 1;
  margin-right: 10px;
}

.send-button {
  flex-shrink: 0;
}


.messageBox {
  display: flex;
  align-items: flex-start; /* 将头像和文本第一行对齐 */
  margin-bottom: 10px;
}

.messageBox img {
  width: 40px; /* 调整头像大小 */
  height: 40px;
  border-radius: 50%;
  margin-right: 10px;
  margin-left: 10px;
}

.messageContent {
  max-width: 70%; /* 调整发送信息宽度 */
  padding: 10px;
  border-radius: 8px;
  background-color: #f0f0f0;
  text-align: left; /* 文本左对齐 */
  word-wrap: break-word; /* 当文本过长时自动换行 */
}

.messageTime {
  font-size: 12px;
  color: #999;
  margin-left: 10px;
  margin-top: 5px; /* 将发送时间与文本分隔开 */
}

.ownMessage {
  flex-direction: row-reverse;
  align-items: flex-end; /* 将发送时间放置在最下方的贴右位置 */
}

.otherMessage {
  flex-direction: row;
  align-items: flex-end; /* 将发送时间放置在最下方的贴左位置 */
}

.online-dot {
  position: absolute;
  top: 0;
  left: 0;
  z-index: 1;
  width: 10px;
  height: 10px;
  background-color: #01c201;
  border-radius: 50%;
}
.message-badge .el-badge__content {
  position: absolute;
  bottom: 5px; /* Adjust to your desired position */
  left: 5px; /* Adjust to your desired position */
  background-color: #f56c6c; /* Red background for visibility */
  color: white; /* White text color */
}
</style>

